import vue from 'vue'
import Vuex from 'vuex'
import router, {resetRouter} from '../router'
import createPersistedState from 'vuex-persistedstate'
vue.use(Vuex)

function addNewRoute(menuList) {
    //循环菜单列表
    console.log(menuList)

    //获取路由列表
    let routes = router.options.routes
    //输出路由列表
    console.log(routes)
    //循环路由列表
    routes.forEach(routeItem=>{
        //判断是否是Index路由
        if (routeItem.path==="/Index") {
            //添加子路由
            menuList.forEach(menu=>{
                //添加子路由
                let childRoute={
                    path:'/'+menu.menuclick,
                    name:menu.menuname,
                    meta:{
                        title:menu.menuname,
                    },
                    component:()=>import('../components/'+menu.menucomponent)
                }
                //添加子路由
                routeItem.children.push(childRoute)
            })
        }
    })
    resetRouter()//重置路由
    router.addRoutes(routes)//添加路由
}

export default new Vuex.Store({
    //状态
    state:{
        menu:[]
    },
    //同步方法
    mutations:{
        //设置菜单
        setMenu(state,menuList) {
            state.menu=menuList
            //添加路由
            addNewRoute(menuList)
        },
        //设置路由
        setRouter(state,menuList) {
            //添加路由
            addNewRoute(menuList)
        }
    },
    //异步方法
    getters:{
        //获取菜单
        getMenu(state){
            return state.menu
        }
    },
    plugins:[createPersistedState()]//持久化
})
